package com.hs.ding.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hs.ding.pojo.Need;
import com.hs.ding.pojo.Vehicle;
import com.hs.ding.service.INeedService;
import com.hs.ding.service.IVehicleService;
import com.hs.ding.utils.NumberGeneratorUtils;
import com.hs.dto.ResultBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author YingFeng
 * @since 2022-06-14
 */
@CrossOrigin
@RestController
@RequestMapping("/need")
public class NeedController {

    @Autowired
    private INeedService iNeedService;

    @Autowired
    private IVehicleService iVehicleService;


    @GetMapping("page")
    public ResultBean findAllByPage(Integer currentPage, Integer pageSize,String inputOrder,String inputName,String inputDeparture){

        //插入操作
        iNeedService.insertNeedList();

        //条件构造器
        LambdaQueryWrapper<Need> qw = new LambdaQueryWrapper<>();

        if (StringUtils.hasText(inputOrder)){
            qw.like(Need::getOrderId,inputOrder);
        }
        if (StringUtils.hasText(inputName)){
            qw.like(Need::getCName,inputName);
        }
        if (StringUtils.hasText(inputDeparture)){
            qw.like(Need::getRoute,inputDeparture);
        }


        qw.eq(Need::getOStatus,0);

        //分页构造器
        IPage<Need> page = new Page<>(currentPage,pageSize);

        //添加排序条件，根据sort进行排序
        qw.orderByAsc(Need::getCTime);

        //分页查询
        iNeedService.page(page,qw);


        ResultBean ok = ResultBean.OK();
        ok.setData(page);

        return ok;
    }

    @PutMapping("submit")
    public ResultBean updateStatus(@RequestBody List<Need> arr){

        System.out.println("arr= " + arr);

        for (Need need : arr) {
            need.setOStatus(1);

            /**
             * 把o_status状态变为1 的订单的订单号  同时设置到 整车调度模块 的 订单号信息里面
             * 并把v_status 状态设置为0
             * 并随机生成 字符串类型的 单号；
             */

            Vehicle vehicle = new Vehicle();
            vehicle.setOrderId(need.getOrderId());
            vehicle.setvStatus(0);
            vehicle.setvOrderId(NumberGeneratorUtils.randomNumber());


            iVehicleService.save(vehicle);


        }

        boolean b = iNeedService.updateBatchById(arr);

        if (b) {
            return ResultBean.OK("提交成功");
        }

        return ResultBean.ERROR("提交失败");
    }

}
